﻿using LineFocus.Nikcron.Common;
using LineFocus.Nikcron.Session;
using Nickron.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LineFocus.Nikcron.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// User & Role Object
        /// </summary>
        protected virtual new CustomPrincipal User
        {
            get { return HttpContext.User as CustomPrincipal; }
        }
        /// <summary>
        /// Add New User Function for all offices
        /// </summary>
        /// <param name="Office"></param>
        /// <param name="OfficeType"></param>
        public void AddNewUser(Office Office, OfficeTypes OfficeType)
        {
            ApplicationDBContext db = new ApplicationDBContext();
            User User = new User();
            bool IsRecordInserted = false;
            Role Role = db.Roles.Where(r => r.Name == OfficeType.ToString()).FirstOrDefault();
            State State = db.States.Where(s => s.Name == Office.Address.State).FirstOrDefault();
            Country Country = db.Countries.Where(c=>c.Id == State.CountryId).FirstOrDefault();
            string Login = string.Empty;
            string Prefix = string.Empty;
            User.OfficeId = Office.Id;
            User.RoleId = Role.Id;
            User.IsNewUser = true;
            User.IsResetPassword = true;
            switch (OfficeType)
            { 
                case OfficeTypes.Stockhouse:
                    Prefix = Constants.STOCKHOUSE_SHORTCODE;
                    break;
                
                case OfficeTypes.Distributor:
                    Prefix = Constants.DISTRIBUTOR_SHORTCODE;
                    break;

                case OfficeTypes.Dealer:
                    Prefix = Constants.DEALER_SHORTCODE;
                    break;

                case OfficeTypes.Retailer:
                    Prefix = Constants.RETAILER_SHORTCODE;
                    break;
            }
            Prefix += Country.Name[0].ToString();
            Prefix += State.ShortCode;

            while (!IsRecordInserted)
            {
                Login = Randomizer.GetRandomNumber(Prefix, 6);

                if (!db.People.OfType<User>().Any(u => u.Username == Login))
                {
                    User.Username = Login;
                    db.People.AddObject(User);
                    db.SaveChanges();
                    IsRecordInserted = true;
                }
            }
            
        }
    }
}
